﻿using Spire.Xls;
using System;
using System.IO;
using System.Text;

namespace ExcelConverter
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                string[] AllExcelFilePaths = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.xls");
                if (AllExcelFilePaths.Length > 0)
                {
                    Console.WriteLine($"检测到{AllExcelFilePaths.Length}个Excel文件");
                    for (int i = 0; i < AllExcelFilePaths.Length; i++)
                    {
                        ConvertToCSV(AllExcelFilePaths[i], 0);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(ex.Message);
                Console.ResetColor();
                Console.ReadLine();
            }
            finally
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("处理完成,按任意键退出");
                Console.ResetColor();
                Console.ReadKey();
            }
        }

        private static void ConvertToCSV(string filePath,int sheetindex)
        {
            FileInfo info = new FileInfo(filePath);
            Console.WriteLine($"处理:{info.Name}");
            Workbook workbook = new Workbook();
            workbook.LoadFromFile(filePath);
            //获取第一张工作表
            Worksheet sheet = workbook.Worksheets[sheetindex];
            string savePath = $"{info.DirectoryName}\\{info.Name.Replace(info.Extension, "")}.txt";
            //保存为csv格式
            sheet.SaveToFile(savePath, "\t", Encoding.UTF8);
            Console.WriteLine($"结果路径:{savePath}");
        }
    }
}